#include "TcpServer.hpp"
#include "Protocol.hpp"
#include <memory>

using namespace ns_tcpserver;
using namespace ns_protocol;

static void Usage(const std::string& process)
{
    std::cout << "\nUsage: " << process << "port\n" << std::endl;
}

static Response calculatorHelper(const Request& req)
{
    Response resp(0, 0);
    switch (req.op_)
    {
    case '+': 
        resp.result_ = req.x_ + req.y_;
        break;
    case '-':
        resp.result_ = req.x_ - req.y_;
        break;
    case '*':
        resp.result_ = req.x_ * req.y_;
        break;
    case '/':
        if (0 == req.y_) resp.code_ = 1;
        else
            resp.result_ = req.x_ / req.y_;
        break;
    case '%':
        if (0 == req.y_) resp.code_ = 2;
        else
            resp.result_ = req.x_ % req.y_;
        break;
    default:
        resp.code_ = 3;
        break;
    }
    return resp;
}

void calculator(int sock)
{
    while (true)
    {
        std::string str = Recv(sock); // 在这里我们读到了一个请求
        Request req;
        req.Deserialized(str);
        Response resp = calculatorHelper(req);
        std::string respString = resp.Serialize(); // 对计算结果进行序列化
        Send(sock, respString);
    }
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::unique_ptr<ns_tcpserver::TcpServer> server(new TcpServer(atoi(argv[1])));
    server->BindService(calculator);
    server->Start();

    return 0;
}